package com.hailan.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author hailan
 * @version 1.0
 * @className ReadWriteLockDemo
 * @description TODO
 * @date 2020-09-01 22:16
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock cache = new MyCacheLock();
        MyCache cache1 = new MyCache();
        //写入
        for (int i = 0; i <= 5 ; i++) {
            final int temp = i;
            new Thread(()->{
                cache1.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }

        //读取
        for (int i = 0; i <= 5 ; i++) {
            final int temp = i;
            new Thread(()->{
                cache1.get(temp+"");
            },String.valueOf(i)).start();
        }

    }
}

/**自定义缓存
 * @author hailan
 * @description //TODO
 * @date 22:16 2020/9/1 0001
 * @param
 * @return
 **/
class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();

    //寸，写
    public void put(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"写入"+key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入ok"+key);
    }

    //取 ，读
    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"读取"+key);
        map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取ok"+key);
    }

}


class MyCacheLock{
    private volatile Map<String,Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //寸，写
    public void put(String key,Object value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入ok"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }

    }

    //取 ，读
    public void get(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取ok"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

}
